跳到主要内容

Kubernetes 自动扩缩容

概述

Kubernetes 提供了两种主要的自动扩缩容机制:

  • HPA (Horizontal Pod Autoscaler):水平扩缩容,调整 Pod 数量
  • VPA (Vertical Pod Autoscaler):垂直扩缩容,调整 Pod 资源配置

水平扩展 (HPA)

基本概念

HPA 通过监控 Pod 的资源使用情况(如 CPU、内存)或自定义指标,自动调整 Deployment、ReplicaSet 或 StatefulSet 中 Pod 的副本数量。

工作原理

负载增加 → 资源使用率上升 → 触发扩容 → 增加 Pod 数量
负载减少 → 资源使用率下降 → 触发缩容 → 减少 Pod 数量

前置条件

# 1. 确保 Metrics Server 已安装并运行
kubectl get deployment metrics-server -n kube-system

# 2. Pod 必须设置资源请求 (requests)

实际应用示例

假设我们有一个运行在 Kubernetes 上的 Web 应用程序,部署为一个 Deployment,并暴露为一个 Service 供外部访问。该应用程序处理用户的 Web 请求,并随着用户流量的增加或减少需要相应地调整 Pod 的数量。

1. 创建应用 Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 2
selector:
matchLabels:
app: webapp
template:
metadata:
labels:
app: webapp
spec:
containers:
- name: webapp
image: nginx:1.20
ports:
- containerPort: 80
resources:
requests:
cpu: 100m # 必须设置,HPA 依赖此值
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
---
apiVersion: v1
kind: Service
metadata:
name: webapp-service
spec:
selector:
app: webapp
ports:
- port: 80
targetPort: 80
type: ClusterIP

2. 创建 HPA(命令行方式)

# 简单创建 HPA
kubectl autoscale deployment webapp --cpu-percent=80 --min=2 --max=5

# 查看 HPA 状态
kubectl get hpa
kubectl describe hpa webapp

3. 创建 HPA(YAML 方式)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: webapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # CPU 使用率达到 70% 时扩容
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80 # 内存使用率达到 80% 时扩容
behavior:
scaleUp:
stabilizationWindowSeconds: 60 # 扩容稳定窗口
policies:
- type: Percent
value: 100 # 每次最多扩容 100%
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300 # 缩容稳定窗口
policies:
- type: Percent
value: 50 # 每次最多缩容 50%
periodSeconds: 60

4. 监控和调整

# 查看 HPA 状态
kubectl get hpa
# 输出示例:
# NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
# webapp-hpa Deployment/webapp 15%/70%, 25%/80% 2 10 2 5m

# 详细查看 HPA 信息
kubectl describe hpa webapp-hpa

# 查看 Pod 状态
kubectl get pods -l app=webapp

# 实时监控 HPA 变化
kubectl get hpa -w

5. 测试扩缩容

# 压力测试触发扩容
kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh
# 在容器内执行:
while true; do wget -q -O- http://webapp-service; done

# 观察扩容过程
kubectl get hpa -w
kubectl get pods -l app=webapp -w

垂直扩展 (VPA)

基本概念

VPA 自动调整 Pod 的 CPU 和内存请求/限制,而不是调整 Pod 数量。它通过分析历史资源使用情况来推荐或自动设置合适的资源配置。

VPA 工作模式

1. Off 模式(仅建议)

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: webapp-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
updatePolicy:
updateMode: "Off" # 只提供建议,不自动更新

2. Initial 模式(仅新 Pod)

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: webapp-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
updatePolicy:
updateMode: "Initial" # 只在创建新 Pod 时应用建议

3. Auto 模式(自动更新)

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: webapp-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
updatePolicy:
updateMode: "Auto" # 自动更新现有 Pod(需要重启)
resourcePolicy:
containerPolicies:
- containerName: webapp
maxAllowed:
cpu: 2
memory: 4Gi
minAllowed:
cpu: 100m
memory: 128Mi
controlledResources: ["cpu", "memory"]

VPA 安装

# 克隆 VPA 仓库
git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler/

# 安装 VPA
./hack/vpa-install.sh

# 验证安装
kubectl get pods -n kube-system | grep vpa

VPA 使用示例

# 创建 VPA
kubectl apply -f webapp-vpa.yaml

# 查看 VPA 建议
kubectl describe vpa webapp-vpa

# 输出示例:
# Status:
# Recommendation:
# Container Recommendations:
# Container Name: webapp
# Lower Bound:
# Cpu: 100m
# Memory: 128Mi
# Target:
# Cpu: 250m # VPA 建议的 CPU 值
# Memory: 512Mi # VPA 建议的内存值
# Upper Bound:
# Cpu: 500m
# Memory: 1Gi

# 查看更新后的 Pod 资源配置
kubectl get pod webapp-xxx -o yaml | grep -A 6 resources:

高级配置

自定义指标 HPA

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: webapp-custom-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "1000" # 每秒 1000 个请求时扩容

扩缩容策略优化

behavior:
scaleUp:
stabilizationWindowSeconds: 60 # 扩容前稳定 60 秒
policies:
- type: Percent
value: 100 # 最多扩容 100%
periodSeconds: 60
- type: Pods
value: 2 # 或者每次最多增加 2 个 Pod
periodSeconds: 60
selectPolicy: Max # 选择扩容最多的策略
scaleDown:
stabilizationWindowSeconds: 300 # 缩容前稳定 5 分钟
policies:
- type: Percent
value: 50 # 最多缩容 50%
periodSeconds: 60
- type: Pods
value: 1 # 或者每次最多减少 1 个 Pod
periodSeconds: 60
selectPolicy: Min # 选择缩容最少的策略

最佳实践

1. HPA 最佳实践

# ✅ 正确的资源设置
resources:
requests:
cpu: 100m # 必须设置
memory: 128Mi # 建议设置
limits:
cpu: 500m # 建议设置
memory: 512Mi # 建议设置

# ✅ 合理的扩缩容阈值
- CPU: 60-80%
- Memory: 70-85%
- 自定义指标:根据业务特性设定

# ✅ 设置合适的副本数范围
minReplicas: 2 # 保证高可用
maxReplicas: 10 # 防止资源耗尽

2. VPA 最佳实践

# ✅ 渐进式采用
1. 先使用 "Off" 模式观察建议
2. 在测试环境使用 "Auto" 模式
3. 生产环境谨慎使用 "Auto" 模式

# ✅ 设置资源边界
minAllowed:
cpu: 100m # 防止资源过小
memory: 128Mi
maxAllowed:
cpu: 2 # 防止资源过大
memory: 4Gi

3. HPA 与 VPA 协同

# ⚠️ 避免冲突
# 不要让 HPA 和 VPA 同时管理相同的资源指标

# ✅ 推荐组合
# HPA 管理 CPU,VPA 管理内存
# 或者 HPA 管理自定义指标,VPA 管理 CPU/内存

故障排查

常见问题及解决方案

1. HPA 不工作

# 检查 Metrics Server
kubectl get pods -n kube-system | grep metrics-server

# 检查 Pod 是否设置了 requests
kubectl describe pod webapp-xxx | grep -A 5 Requests

# 检查 HPA 状态
kubectl describe hpa webapp-hpa

# 查看 HPA 事件
kubectl get events --field-selector involvedObject.name=webapp-hpa

2. VPA 建议不准确

# 检查历史数据收集时间(建议运行 24 小时以上)
kubectl describe vpa webapp-vpa

# 查看 VPA 组件状态
kubectl get pods -n kube-system | grep vpa

# 检查资源策略配置
kubectl get vpa webapp-vpa -o yaml

3. 扩缩容过于频繁

# 调整稳定窗口
behavior:
scaleUp:
stabilizationWindowSeconds: 120 # 增加稳定时间
scaleDown:
stabilizationWindowSeconds: 600 # 增加稳定时间

监控和告警

Prometheus 监控指标

# HPA 相关指标
- kube_horizontalpodautoscaler_status_current_replicas
- kube_horizontalpodautoscaler_status_desired_replicas
- kube_horizontalpodautoscaler_spec_max_replicas
- kube_horizontalpodautoscaler_spec_min_replicas

# VPA 相关指标
- vpa_recommender_recommendation
- vpa_updater_evictions_total

Grafana 仪表板

{
"targets": [
{
"expr": "kube_horizontalpodautoscaler_status_current_replicas{hpa=\"webapp-hpa\"}",
"legendFormat": "当前副本数"
},
{
"expr": "kube_horizontalpodautoscaler_status_desired_replicas{hpa=\"webapp-hpa\"}",
"legendFormat": "期望副本数"
}
]
}

通过合理配置 HPA 和 VPA,可以实现应用程序的自动扩缩容,提高资源利用率,确保应用性能和可用性。在生产环境中使用时,建议先在测试环境充分验证配置的合理性。